package com.ktr.service.impl;

import com.ktr.dao.KtrInfoDataDao;
import com.ktr.entity.KtrInfoData;
import com.ktr.service.KtrInfoDataService;
import com.ktr.utils.Device;
import com.ktr.utils.DeviceUtils;
import com.bhudy.base.BaseServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.Serializable;
import java.util.List;
import java.util.Map;

/**
 * @Author com.bhudy
 * @Description KtrInfoDataServiceImpl
 * @Date 2019-10-30 23:09:37
 */
@Service
public class KtrInfoDataServiceImpl extends BaseServiceImpl<KtrInfoData, Serializable> implements KtrInfoDataService {

    @Autowired
    private KtrInfoDataDao ktrInfoDataDao;

    @Override
    public int updateKtrInfoData() {
        List<Device> deviceList = DeviceUtils.getInstance().getDeviceList();
        if (deviceList.size() != 0) {
            String sql = "UPDATE `ktr_info_data` SET `ktr_data` = (CASE";
            String ktrInfoId = "";
            String pos = "";
            for (Device device : deviceList) {
                for (Map.Entry<Integer, Double> entry : device.getDeviceDataMap().entrySet()) {
                    sql += " WHEN ( pos = " + entry.getKey() + " and ktr_info_id = " + device.getKtrId() + ") THEN " + entry.getValue() + " ";
                    pos += entry.getKey() + ",";
                }
                ktrInfoId += device.getKtrId() + ",";
            }
            sql += " ELSE 0 END), update_date = now() WHERE (`ktr_info_id` in (";
            sql += ktrInfoId.substring(0, ktrInfoId.length() - 1) + ")) AND pos in (";
            sql += pos.substring(0, pos.length() - 1) + ")";
            return ktrInfoDataDao.updateKtrInfoData(sql);
        } else {
            String sql = "UPDATE `ktr_info_data` SET `ktr_data`='0'";
            return ktrInfoDataDao.updateKtrInfoData(sql);
        }
    }
}
